import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, getCacheTenant } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { getCacheRouter } from '@/utils/menu'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

let count = 0

router.beforeEach(async(to, from, next) => {
  NProgress.start()

  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()

  if (hasToken) {
    console.log('permission', store.dispatch('m_msg/WEBSOCKET_INIT'))
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const tenant = getCacheTenant()
      const routerMenu = getCacheRouter()
      if (tenant && routerMenu) {
        next()
      } else {
        try {
          if (count++ <= 5) {
            // 获取租户
            await store.dispatch('tenant/getCurrentTenant')
              // 获取菜单
            await store.dispatch('menu/getLayoutInAuth')
              // 實時預警websocket
            await store.dispatch('m_msg/WEBSOCKET_INIT')
            next()
          }
          if (to.redirectedFrom) {
            next(to.redirectedFrom)
          } else {
            next()
          }
        } catch (error) {
          //await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})